package actions;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import model.StudentModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;

public class ShowApplicationAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws DbException {

	    // current user
	    String username = request.getUserPrincipal().getName();
	    // the current users application
	    int applicationID = 0;
	    
	    // Make call to alreadyApplied check the current user
	    RowSet applicantInfo = StudentModel.alreadyApplied(username);
	    request.setAttribute("applicantInfo", applicantInfo);

	    // finds if they have application already
	    try {
	        if  (applicantInfo.next()) {
                applicationID = applicantInfo.getInt("student");
                //applicantInfo.previous();
            }
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }

	    // if user already has application
	    if(applicationID != 0){
	        // sets their application to the request scope
	        RowSet application  = StudentModel.fetchApplication(applicationID);
	        request.setAttribute("application", application);
	        return mapping.findForward("applied");
	    }else{
	        // else user needs to make a new application
	        return mapping.findForward("notapplied");
	    }
	}
}
